﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pure.API
{
    /// <summary>
    /// Api权限处理类
    /// </summary>
    public class ApiAuthorize : AuthorizeAttribute, IAuthorizationFilter
    {
        public ApiAuthorize()
        {
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //若是不需要访问的 则直接跳过
            if (IsHaveAllow(context.Filters))
            {
                return;
            }
            //获取用户凭证信息 若无凭证信息 则拒绝访问
            var user = context.HttpContext.User;
            if (user.Claims.FirstOrDefault() == null)
            {
                context.Result = new JsonResult(value: new
                {
                    success = false,
                    errs = new[] { "服务端拒绝访问：你没有权限,或者掉线了" }
                });
            }
            else
            {
                //todo 获取验证权限的信息 判断当前用户凭证是否具有权限(后续需进行特定角色验证在进行处理)
                return;
            }


        }
        /// <summary>
        /// 判断是否不需要权限
        /// </summary>
        /// <param name="filers"></param>
        /// <returns></returns>
        public static bool IsHaveAllow(IList<IFilterMetadata> filers)
        {
            for (int i = 0; i < filers.Count; i++)
            {
                if (filers[i] is IAllowAnonymousFilter)
                {
                    return true;
                }
            }
            return false;

        }
    }
}
